package com.zzzzzz.posts;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import com.zzzzzz.BaseDao;
import com.zzzzzz.common.page.Page;

@Repository
public class ReplyDao extends BaseDao {
	
	private static final String ADD = 									"insert into reply(content, user_id, post_id, add_time, upd_time, status) values (:content, :userId, :postId, :addTime, :updTime, :status)";
	private static final String EDIT = 									"update reply set content = :content, upd_time = :updTime where id = :id";
	private static final String EDIT_STATUS = 							"update reply set status = ?, upd_time = ? where id = ?";
	
	private static final String FIND_REPLYVIEW_BY_POSTID =    			"select r.id, r.content, r.add_time, r.user_id, u.name as user_name, u.pic_id as user_pic_id from reply r inner join user u on r.user_id = u.id where r.post_id = ? and r.status = 0 order by add_time desc";
	private static final String FIND_COUNT_REPLYVIEW_BY_POSTID = 		"select count(1) from reply r inner join user u on r.user_id = u.id where r.post_id = ? and r.status = 0";
	
	protected class ReplyViewRowMapper implements RowMapper<ReplyView> {
		public ReplyView mapRow(ResultSet rs, int rn) throws SQLException {
			ReplyView replyView = new ReplyView();
			replyView.setReplyId(rs.getLong("id"));
			replyView.setContent(rs.getString("content"));
			replyView.setAddTime(rs.getTimestamp("add_time"));
			replyView.setUserId(rs.getLong("user_id"));
			replyView.setUserName(rs.getString("user_name"));
			replyView.setUserPicId(rs.getString("user_pic_id"));
			return replyView;
		}
	}
	
	public void add(Reply reply) {
		Long id = updateForLongKey(ADD, reply);
		reply.setId(id);
	}

	public void edit(Reply reply) {
		update(EDIT, reply);
	}
	
	public void editStatus(Long id, Integer status) {
		update(EDIT_STATUS, status, new Date(), id);
	}
	
	public Page<ReplyView> findReplyViewByPostId(Integer postId, Page<ReplyView> page){
		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("postId", postId);
		
		StringBuilder sql = new StringBuilder(FIND_REPLYVIEW_BY_POSTID);
		sql.append(limit(paramMap, page));
		
		return findPage(page,sql.toString(), FIND_COUNT_REPLYVIEW_BY_POSTID, paramMap, new ReplyViewRowMapper());
	}
}
